﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using NetFrameworkExtensions.Utils;

namespace NetFrameworkExtensions.Collections
{
  public class WeakDictionary<TKey, TValue> : IDictionary<TKey, TValue>
  {
    private Dictionary<TKey, WeakReference<TValue>> inner;

    public WeakDictionary()
    {
      inner = new Dictionary<TKey, WeakReference<TValue>>();
    }

    public WeakDictionary(int capacity)
    {
      inner = new Dictionary<TKey, WeakReference<TValue>>(capacity);
    }

    public void Add(TKey key, TValue value)
    {
      inner.Add(key, new WeakReference<TValue>(value));
    }

    public void Add(KeyValuePair<TKey, TValue> item)
    {
      Add(item.Key, item.Value);
    }

    public bool ContainsKey(TKey key)
    {
      return inner.ContainsKey(key);
    }

    public ICollection<TKey> Keys
    {
      get { return inner.Keys; }
    }

    public ICollection<TValue> Values
    {
      get { return inner.Values.Select(wr => wr.Target).ToList(); }
    }

    public bool Remove(TKey key)
    {
      return inner.Remove(key);
    }

    public bool Remove(KeyValuePair<TKey, TValue> item)
    {
      return Contains(item) && inner.Remove(item.Key);
    }

    public bool TryGetValue(TKey key, out TValue value)
    {
      value = default(TValue);
      WeakReference<TValue> wr;
      if (!inner.TryGetValue(key, out wr))
        return false;
      
      value = wr.Target;
      return true;
    }

    public TValue this[TKey key]
    {
      get
      {
        return inner[key].Target;
      }
      set
      {
        inner[key].Target = value;
      }
    }

    public void Clear()
    {
      inner.Clear();
    }

    public bool Contains(KeyValuePair<TKey, TValue> item)
    {
      return inner.ContainsKey(item.Key) && inner[item.Key].Equals(item.Value);
    }

    public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
    {
      inner.Select(kvp => new KeyValuePair<TKey, TValue>(kvp.Key, kvp.Value.Target)).CopyTo(array, arrayIndex);
    }

    public int Count
    {
      get { return inner.Count; }
    }

    public bool IsReadOnly
    {
      get { return false; }
    }

    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
    {
      return inner.Select(kvp => new KeyValuePair<TKey, TValue>(kvp.Key, kvp.Value.Target)).GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
      return GetEnumerator();
    }
  }
}
